<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/favicon.ico">
    <link rel="canonical" href="https://getbootstrap.com/docs/3.4/examples/signin/">

    <title>Signin Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/dist/css/bootstrap.min.css"
          rel="stylesheet">

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/assets/css/ie10-viewport-bug-workaround.css"
          rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/examples/signin/signin.css"
          rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/assets/js/ie8-responsive-file-warning.js"></script>
    <![endif]-->
    <script src="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/assets/js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>

        .group-status {
            display: none;
        }
    </style>
</head>

<body>

<div class="container">


    <form class="form-signin" action="">
        <h2 class="form-signin-heading">请登陆</h2>
        <label for="inputUsername" class="sr-only">Username</label>
        <input type="text" id="inputUsername" name="username" class="form-control" placeholder="用户名" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" name="password" class="form-control" placeholder="密码" required>
        <div class="checkbox icheck">
            <label>
                <input type="checkbox" value="remember-me" name="rememberme"> 记住我
            </label>
        </div>
        <button type="button" id="userRegister" class="btn btn-link" data-toggle="modal" data-target="#myModal" data-whatever="register">>注册
        </button>
        <button type="button" class="btn btn-primary btn-lg"  data-toggle="modal" data-target="#myModal" data-whatever="login">登陆</button>
    </form>
    <!--      提示消息 -->
</div> <!-- /container -->




<!-- 登陆验证模态 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>

            <div class="modal-body">

                <form class="form-horizontal">
                        <div class="form-group group-status">
                            <label for="username" class="col-sm-2 control-label">账号</label>
                            <div class="col-sm-10">
                                <input type="text" id="username" name="username" class="form-control" value="" placeholder="输入用户名"  autofocus>
                            </div>
                        </div>

                        <div class="form-group group-status">
                            <label for="password" class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" id="password" name="password" class="form-control" value="" placeholder="输入密码" autofocus>
                            </div>
                        </div>
                </form>
                    <div class="form-group">
                            <label for="take" class="col-sm-2 control-label"></label>
                            <div class="col-sm-10">
                                <button id="take">拍照</button>
                            </div>
                    </div>

                    <div class="form-group">
                            <label for="p" class="col-sm-2 control-label"></label>
                            <div class="col-sm-10">
                                <p id="p">点击拍照上传验证</p>
                            </div>
                    </div>

                    <div class="form-group">
                            <label for="v" class="col-sm-2 control-label"></label>
                            <div class="col-sm-10">
                                <video id="v" style="width: 320px;height: 320px;"></video>
                            </div>
                    </div>

                    <div class="form-group">
                            <label for="canvas" class="col-sm-2 control-label"></label>
                            <div class="col-sm-10">
                                <canvas id="canvas" style="display:none;"></canvas>
                            </div>
                    </div>

                    <div class="form-group">
                        <img src="http://placehold.it/320&text=Your%20image%20here%20..." id="photo" alt="photo">

                    </div>


            </div>


            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="commit">提交</button>
            </div>
        </div>
    </div>
</div>







<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="{{url_for('static',filename='js/jqueryv1.12.4.min.js')}}"></script>
<script src="{{url_for('static',filename='js/bootstrap.js')}}"></script>
<script src="{{url_for('static',filename='js/base.js')}}"></script>
<script>

    function postAPI(obj, imgUrl , asyncStatus) {
        $.ajax({
            type: 'post',
            url: imgUrl,
            cache: false,
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify({'data': obj}),
            async: asyncStatus,
            success: function (msgs) {
                window.alert( msgs.news )
                if (msgs.code !== 200) {
                        window.location.reload()
                        //
                } else {
                    if (msgs.url){
                        window.location.href=msgs.url;
                    }else{

                        window.location.reload()
                    }
                }

            }
        })
    }





    function changeState(v) {
        let canvas = document.getElementById('canvas');
        canvas.width = v.videoWidth;
        canvas.height = v.videoHeight;
        canvas.getContext('2d').drawImage(v, 0, 0);
        let data = canvas.toDataURL('image/png');
        document.getElementById('photo').setAttribute('src', data);
        // postAPI(data, '/jieshou')
    }


    function changeText(paizhao) {
        let btn = $('#update-text');
        btn.text(3)
        var time = setInterval(function () {
            btn.text(parseFloat(btn.text()) - 1)
            if (parseFloat(btn.text()) == 0) {
                btn.text('停止拍照')
                clearInterval(time);
                clearTimeout(paizhao)
            }
        }, 1000);
        // $('#update-text').text(data+"s后停止获取")
    }

    function userRegister() {

    }

    !(function () {
        // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {
                // 首先，如果有getUserMedia的话，就获得它
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

                // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }

                // 否则，为老的navigator.getUserMedia方法包裹一个Promise
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }
        const constraints = {
            video: true,
            audio: false
        };
        let videoPlaying = false;
        let v = document.getElementById('v');
        let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(stream => {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in v) {
                v.srcObject = stream;
            } else {
                // 防止再新的浏览器里使用它，应为它已经不再支持了
                v.src = window.URL.createObjectURL(stream);
            }
            v.onloadedmetadata = function (e) {
                v.play();
                videoPlaying = true;
            };
        }).catch(err => {
            console.error(err.name + ": " + err.message);
        })
        document.getElementById('take').addEventListener('click', function () {
            if (videoPlaying) {
                // setTimeout("changeState(v)",1000 );
                // let paizhao = setInterval("changeState(v)", 500);
                let paizhao = changeState(v);
                // changeText(paizhao)
                // window.location.reload()
            }
        }, false);
    })();


    $('#myModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var recipient = button.data('whatever') // Extract info from data-* attributes
        var modal = $(this)
        // modal.find('.modal-title').text('加减余额 toId ' + recipient)
        // modal.find('#numIncreaseOrDecreaseUserId').val(recipient)
        console.log('recipient: ', recipient)
        if ( recipient==='login' ){
            // 更改模态框标题
            modal.find('#myModalLabel').text('登陆人脸验证')
            modal.find('#commit').on('click', function (){
                let inputUsername = $('#inputUsername').val()
                let inputPassword = $('#inputPassword').val()
                let src = modal.find('#photo').attr('src')
                // console.log('输出内容：',inputUsername, inputPassword, src)
                let obj = {'username':inputUsername, 'password':inputPassword, 'src':src}
                postAPI(obj, '/login', false)
            });
        } else {
            modal.find('#myModalLabel').text('注册人脸录入')
            // modalForm 显示
            modal.find('.group-status').show()
            modal.find('#commit').on('click', function (){
                let username = modal.find('#username').val()
                let password = modal.find('#password').val()
                let src = modal.find('#photo').attr('src')
                console.log('输出内容：',username, password, src)
                let obj = {'username':username, 'password':password, 'src':src}
                postAPI(obj, '/register', false)
            });
        }

        $('#myModal').on('hidden.bs.modal', function (e) {
            window.location.reload() //关闭模态框，刷新页面
        })

    })

</script>


</body>
</html>
